package com.suxii.netty_demo.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.suxii.Thread.NettyThread;
import com.suxii.adapter.ChatListAdapter;
import com.suxii.adapter.LeftMessageAdapter;
import com.suxii.adapter.MessageAdapter;
import com.suxii.adapter.animator.FadeInAnimator;
import com.suxii.netty_demo.MainActivity;
import com.suxii.netty_demo.R;
import com.suxii.netty_demo.fragment.MessageFragment;
import com.suxii.pojo.ChatMsg;
import com.suxii.pojo.MessageMsg;
import com.suxii.pojo.MyMsg;
import com.suxii.service.MyNettyService;
import com.suxii.utils.Global;
import com.suxii.widget.LeftListView;
import com.suxii.widget.NoBar;
import com.suxii.widget.dialog.CustomDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class ChatActivity extends AppCompatActivity {
    /*
    自定义控件需要的变量
    TODO 临时处理
     */
    private RecyclerView messageList;
    public LeftMessageAdapter messageAdapter;

    /*
    作为全局变量，便于更新界面绘制
     */
    public static RecyclerView chat_list=null;
    public List<MyMsg> data;
    public static ChatListAdapter chatListAdapter;

    private EditText chat_in;
    private TextView title;
    private Button send_btn;

    private LeftListView leftListView;

    private Button clear;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        NoBar.setNoBar(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_main);

        Log.e("aa",Global.noticeUid+"");


        // TODO 不知道为什么put传参不能用，暂时未解决
        // 获取通知的参数
        if (Global.noticeUid!=0){
            Global.setUuid(Global.noticeUid);
            Global.noticeUid=0;
        }

        chat_list=findViewById(R.id.chat_list);
        chat_in=findViewById(R.id.chat_in);
        send_btn=findViewById(R.id.chat_send_btn);
        title=findViewById(R.id.textView);
        title.setText(Global.nameOfUid.get(String.valueOf(Global.uuid)));

        messageList = findViewById(R.id.test_list);

        leftListView=findViewById(R.id.left_view);

        clear=findViewById(R.id.chat_left_clear);

        //监听事件
        listener();

        //加载左边列表,聊天消息
        new Thread(this::start,"线程更新消息").start();
        new Thread(this::leftList,"线程更新列表").start();



    }

    private CustomDialog mDialog;
    private void listener(){
        //
        chat_in.setOnClickListener(view -> {
            chat_list.scrollToPosition(chatListAdapter.getItemCount() - 1);
        });

        //清空聊天信息
        clear.setOnClickListener(view->{
            mDialog.setCanotBackPress();
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.show();

        });

        //文本框监听事件

        //弹出窗口
        mDialog=new CustomDialog(this, "温馨提示", "确定将清空聊天消息", "确定",new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                deleteMsg();
                chatListAdapter.deleteData();
                Toast.makeText(ChatActivity.this,"已清空",Toast.LENGTH_LONG).show();
            }
        },"取消");

    }

/*
    private boolean isFocus=true;

    @Override
    protected void onStop() {
        super.onStop();
        isFocus=false;
        Log.e("aa","stopchat");
    }

    @Override
    protected void onStart() {
        super.onStart();
        isFocus=true;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        try {
            Thread.sleep(400);
            if (!hasFocus&&isFocus){
                chat_list.scrollToPosition(chatListAdapter.getItemCount() - 1);
                Log.e("aa","fouces");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }*/

    private void start(){
        data = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        chat_list.setLayoutManager(manager);
        chatListAdapter = new ChatListAdapter(data, this);
        //加载本地缓存消息
        chatListAdapter.findMessage2(Global.uuid);
        //chatListAdapter.findMessage(Global.uuid);
        chat_list.setAdapter(chatListAdapter);
        chat_list.scrollToPosition(chatListAdapter.getItemCount() - 1);
        // 列表更新动画
        chat_list.setItemAnimator(new FadeInAnimator());

        isNull=chatListAdapter.getItemCount()==0;
    }

    private void leftList(){

        LinearLayoutManager manager = new LinearLayoutManager(this);
        messageList.setLayoutManager(manager);

        messageAdapter = new LeftMessageAdapter(Global.messageMsgList, this);
        messageList.setAdapter(messageAdapter);

        messageAdapter.setOnItemClickListener(pos -> {
            MessageFragment.messageAdapter.reMoveCout(Global.uuid,chatListAdapter.getNewMessage());

            if (!Integer.valueOf(pos.getName()).equals(Global.uuid)) {
                Global.setUuid(Integer.valueOf(pos.getName()));
                new Thread(() -> run(Integer.parseInt(pos.getName())), "线程更新消息").start();
            }else {
                leftListView.moveBackAnim();
            }
        });
    }
    private void run(int uuid){
        chatListAdapter.findMessage2(uuid);
        title.post(() -> {
            title.setText(Global.nameOfUid.get(String.valueOf(uuid)));
        });
        leftListView.post(()->{
            leftListView.moveBackAnim();
        });
    }

    private boolean deleteMsg(){
        File file = new File(getFilesDir(), Global.uuid + "_message.sx");
        if (file.delete()) {
            isNull=true;
            if (MessageFragment.messageAdapter!=null){
                MessageFragment.messageAdapter.removeMessage();
            }
            return true;
        }
        return false;
    }

    public void msg_send(View view) {
        String text =chat_in.getText().toString();
        if (!text.isEmpty()) {
            //发消息
            NettyThread.channel.writeAndFlush(new ChatMsg("", Global.uid, text, Global.uuid));
            chatListAdapter.addData(new MyMsg(1, text));
            chat_list.scrollToPosition(chatListAdapter.getItemCount() - 1);

            chat_in.setText("");

            // 保存聊天消息
            chatListAdapter.savaMessage2(Global.uuid);
        }

    }

    private boolean isNull;
    private void isHavaMsg(){
        if (isNull) {
            Log.e("aa", "coutchat" + chatListAdapter.getItemCount());
            if (chatListAdapter.getItemCount() > 0) {
                boolean isHave = Global.messageMsgList.stream().anyMatch(o -> !o.getName().equals(String.valueOf(Global.uuid)));
                Log.e("aa", isHave + "");
                if (isHave){
                    Log.e("aa","保存这个文件");
                    MessageFragment.messageAdapter.findMessage();
                }

            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (leftListView.isOpen){
                leftListView.moveBackAnim();
            }else {
                isHavaMsg();
                if (!isNull) {
                    //更新小消息
                    MessageFragment.messageAdapter.reMoveCout(Global.uuid, chatListAdapter.getNewMessage());
                    //Log.e("aa","更新小消息");
                }
                chat_list = null;
                //finishAfterTransition();
                finish();
                return false;
            }
        }
        return false;
    }
}